package hsb.ruoyi.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usthe.sureness.mgt.SurenessSecurityManager;
import com.usthe.sureness.processor.exception.*;
import com.usthe.sureness.subject.SubjectSum;
import hsb.ruoyi.common.config.security.SurenessContextHolder;
import hsb.ruoyi.common.constant.HttpStatus;
import hsb.ruoyi.common.core.domain.AjaxResult;
import hsb.ruoyi.common.exception.ServiceException;
import hsb.ruoyi.common.utils.StringUtils;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.ws.rs.container.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * @author 胡帅博
 * @date 2023/1/2 0:24
 */
@Provider
@PreMatching
public class SurenessFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Inject
    ObjectMapper JSON;

    private static final Logger log = LoggerFactory.getLogger(SurenessFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) {
        try {
            SurenessContextHolder.clear();
            SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(requestContext);
            // You can consider using SurenessContextHolder to bind subject in threadLocal
            // if bind, please remove it when end
            if (subject != null) {
             //   SurenessContextHolder.bindSubject(subject);
            }
        } catch (IncorrectCredentialsException | UnknownAccountException | ExpiredCredentialsException e1) {
            String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", requestContext.getUriInfo().getPath());
         //   requestContext.abortWith(Response.status(200).entity(msg).build());
            throw new ServiceException(msg, HttpStatus.UNAUTHORIZED);
        } catch (NeedDigestInfoException e4) {
            requestContext.abortWith(Response.status(401).header("WWW-Authenticate", e4.getAuthenticate()).build());
        } catch (UnauthorizedException e5) {

            String msg = StringUtils.format("请求访问：{}，访问受限，无法访问系统资源", requestContext.getUriInfo().getPath());
            throw new ServiceException(msg, HttpStatus.FORBIDDEN);
          // requestContext.abortWith(Response.status(403).entity(e5.getMessage()).build());

        } catch (RuntimeException e) {

            requestContext.abortWith(Response.status(500).entity(e.getMessage()).build());
        }

       // HttpServerRequest request = rc.request();
//        try {
//            SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(requestContext);
//
//        } catch (IncorrectCredentialsException | UnknownAccountException | ExpiredCredentialsException e1) {
//          //  String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.path());
//         //   log.debug(msg);
//          //  ServletUtils.renderString(rc.response(), msgResult(401, msg));
//            requestContext.abortWith(Response.status(403).entity(e1.getMessage()).build());
//        } catch (NeedDigestInfoException e4) {
//            // log.debug("you should try once again with digest auth information");
//            // rc.fail(401, e4);
//        } catch (UnauthorizedException e5) {
//          ///  String msg = StringUtils.format("请求地址'{}',权限校验失败'{}'", request.path(), e5.getMessage());
//          //  log.debug(msg);
//         //   ServletUtils.renderString(rc.response(), msgResult(403, msg));
//        } catch (RuntimeException e) {
//            log.error("other exception happen12: ", e);
//            //rc.fail(500, e);
//            //todo 后边搞成全局异常处理
//          // rc.end();
//        }


    }


    @SneakyThrows
    public String msgResult(int code, String msg) {
        return JSON.writeValueAsString(AjaxResult.error(code, msg));
    }



    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        //SurenessContextHolder.clear();
    }

}
